package se.thoka.twt.client.json;

import java.util.HashSet;
import java.util.Set;

import com.google.gwt.json.client.JSONValue;
import com.gwtent.reflection.client.Field;
import com.gwtent.reflection.client.Type;

public class JSONFieldParserUtil {
	
	public interface Parser {
		boolean accept(Field field);
		Object parse(Field field, JSONValue value);
	}

	private static JSONFieldParserUtil instance;
	
	public static JSONFieldParserUtil getInstance() {
		if (instance == null) {
			instance = new JSONFieldParserUtil();
		}
		return instance;
	}
	
	private Set<Parser> parsers;
	
	private JSONFieldParserUtil() {
		parsers = new HashSet<JSONFieldParserUtil.Parser>();
		parsers.add(new JSONPrimitivesParser());
		parsers.add(new JSONArrayParser());
	}
	
	public Parser getParser(Field field) {
		for (Parser parser : parsers) {
			if (parser.accept(field)) {
				return parser;
			}
		}
		return null;
	}
	
	public static boolean isType(Type type, Class<?> clazz) {
		return type.getParameterizedQualifiedSourceName().equals(clazz.getName());
	}
	
	
}
